﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

namespace Sparrow.VisualStudio.Debugger.RouteVisualizer
{
    [Serializable]
    public class JsonObject
    {
        public JsonObject(object obj)
        {
            if (obj != null)
            {
                var json = new JavaScriptSerializer();

                this.Type = obj.GetType();
                this.JsonContent = json.Serialize(obj);
            }
        }

        public Type Type
        {
            get;
            set;
        }

        public string JsonContent
        {
            get;
            set;
        }

        public virtual object Deserialize()
        {
            if (this.Type != null)
            {
                try
                {
                    var json = new JavaScriptSerializer();
                    return json.Deserialize(JsonContent, Type);
                }
                catch
                {
                    if (string.IsNullOrWhiteSpace(this.JsonContent)==false)
                    {
                        return this.JsonContent;
                    }
                    else
                    {
                        return this.Type.ToString();
                    }
                }
            }
            else if (string.IsNullOrWhiteSpace(this.JsonContent) == false)
            {
                return this.JsonContent;
            }
            else
            {
                return null;
            }
        }
    }
}
